#include <QFile>
#include "gpio.h"

GPIOError GPIO::open( unsigned int pin )
{
	QFile gpioFile( "/sys/class/gpio/export" );
	if( !gpioFile.open( QIODevice::WriteOnly ) )
		return GPIO_ERROR_NONE;

	gpioFile.write( QString::number( pin ).toLatin1() ); // Open specific pin file
	gpioFile.close();
	return GPIO_ERROR_NONE;
}

GPIOError GPIO::close( unsigned int pin )
{
	QFile gpioFile( "/sys/class/gpio/unexport" );
	if( !gpioFile.open( QIODevice::WriteOnly ) )
		return GPIO_ERROR_OPEN;

	gpioFile.write( QString::number( pin ).toLatin1() ); // Unload pin file
	gpioFile.close();
	return GPIO_ERROR_NONE;
}

GPIOError GPIO::direction( unsigned int pin, unsigned int dir )
{
	QFile gpioFile( QString( "/sys/class/gpio/gpio%1/direction" ).arg( pin ) );
	if( !gpioFile.open( QIODevice::WriteOnly ) )
		return GPIO_ERROR_OPEN;

	gpioFile.write( dir == GPIO_IN ? "in" : "out" ); // Change GPIO direction
	gpioFile.close();
	return GPIO_ERROR_NONE;
}

GPIOError GPIO::write( unsigned int pin, bool val )
{
	QFile gpioFile( QString( "/sys/class/gpio/gpio%1/value" ).arg( pin ) );
	if( !gpioFile.open( QIODevice::WriteOnly ) )
		return GPIO_ERROR_OPEN;

	gpioFile.write( val == true ? "1" : "0" ); // Output GPIO value
	gpioFile.close();
	return GPIO_ERROR_NONE;
}

GPIOError GPIO::read( unsigned int pin, bool & val )
{
	QFile gpioFile( QString( "/sys/class/gpio/gpio%1/value" ).arg( pin ) );
	if( !gpioFile.open( QIODevice::ReadOnly ) )
		return GPIO_ERROR_OPEN;

	gpioFile.read( 1 ) == "1" ? val = true : val = false; // Read GPIO value
	return GPIO_ERROR_NONE;
}
